package com.nanhai.buddhist.college.module.study.framework.datapermission;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanhai.buddhist.college.framework.common.enums.UserTypeEnum;
import com.nanhai.buddhist.college.framework.datapermission.core.rule.DataPermissionRule;
import com.nanhai.buddhist.college.framework.mybatis.core.dataobject.BaseDO;
import com.nanhai.buddhist.college.framework.mybatis.core.util.MyBatisUtils;
import com.nanhai.buddhist.college.framework.security.core.LoginUser;
import com.nanhai.buddhist.college.framework.security.core.util.SecurityFrameworkUtils;
import net.sf.jsqlparser.expression.Alias;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

//@AllArgsConstructor
//@Component
public class StudyStudentDataPermissionRule implements DataPermissionRule {


    private final Map<String, String> teacherColumns = new HashMap<>();

    private final Set<String> TABLE_NAMES = new HashSet<>();






    @PostConstruct
    public void initTable(){
        this.addTeacherColumn("t_class_clock_record","clock_user_id");
        this.addTeacherColumn("t_attendance_management","user_id");

    }


    @Override
    public Set<String> getTableNames() {
        return TABLE_NAMES;
    }

    @Override
    public Expression getExpression(String tableName, Alias tableAlias) {

        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (loginUser == null) {
            return null;
        }
        // 只有管理员类型的用户，才进行数据权限的处理
        if (ObjectUtil.notEqual(loginUser.getUserType(), UserTypeEnum.STUDENT.getValue())) {
            return null;
        }

        //
        String columnName = teacherColumns.get(tableName);
        return new EqualsTo(MyBatisUtils.buildColumn(tableName, tableAlias, columnName),
                new StringValue(loginUser.getId()));
    }




    public void addTeacherColumn(Class<? extends BaseDO> entityClass, String columnName) {
        String tableName = TableInfoHelper.getTableInfo(entityClass).getTableName();
        addTeacherColumn(tableName, columnName);
    }


    public void addTeacherColumn(String tableName, String columnName) {
        teacherColumns.put(tableName, columnName);
        TABLE_NAMES.add(tableName);
    }
}
